﻿Imports System.Reflection

Public Class Descricao
    Inherits System.Attribute

    Private _descricao As String
    Public ReadOnly Property Descricao() As String
        Get
            Return _descricao
        End Get
    End Property

    Public Sub New(ByVal _descricao As String)
        Me._descricao = _descricao
    End Sub

    Protected Shared _dicionarioDescricoes As Dictionary(Of String, Descricao)

    Public Shared Function Descreve(ByVal _enum As [Enum]) As String
        Dim _descricao As String
        Dim _tipo As Type
        Dim _chave As String
        Dim _fieldInfo As FieldInfo
        Dim _descricoesNoEnum As Descricao()

        If _dicionarioDescricoes Is Nothing Then
            _dicionarioDescricoes = New Dictionary(Of String, Descricao)
        End If

        If _enum IsNot Nothing Then
            _tipo = _enum.GetType()
            _chave = _tipo.FullName & "." & _enum.ToString

            If _dicionarioDescricoes.ContainsKey(_chave) Then
                _descricao = _dicionarioDescricoes(_chave).Descricao
            Else
                _fieldInfo = _tipo.GetField(_enum.ToString())
                _descricoesNoEnum = CType(_fieldInfo.GetCustomAttributes(GetType(Descricao), False), Descricao())

                
                If _descricoesNoEnum IsNot Nothing AndAlso _descricoesNoEnum.Length > 0 Then
                    _dicionarioDescricoes.Add(_chave, _descricoesNoEnum.First)
                    _descricao = _dicionarioDescricoes(_chave).Descricao
                Else
                    _descricao = _enum.ToString
                End If

            End If

        Else
            _descricao = _enum.ToString
        End If

        Return _descricao
    End Function


End Class
